package com.boom.springapp.javafxdemo.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;

import org.springframework.stereotype.Component;

import com.boom.springapp.javafxdemo.common.Picture;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ImageDownloader {

    /**
     * 下载单张图片
     */
    public void downloadImage(String imageUrl, String outputDir, String prefix) {
        try {
            // 确保输出目录存在
            Path outputPath = Paths.get(outputDir);
            Files.createDirectories(outputPath);

            // 获取图片文件名
            String[] parts = imageUrl.split("/");
            String imgName = parts[parts.length - 1];
            Path outputFile = outputPath.resolve(prefix + "_" + imgName);

            // 如果文件已存在，跳过下载
            if (Files.exists(outputFile)) {
                log.info("图片已存在，跳过下载: " + outputFile.toString());
                return;
            }

            // 发送HTTP请求并下载图片
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            try (InputStream inputStream = connection.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(outputFile.toFile())) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            log.info("图片下载成功: " + outputFile.toString());

        } catch (Exception e) {
            log.error("下载图片失败 (" + imageUrl + "): " + e.getMessage(), e);
        }
    }

    /**
     * 多线程下载多张图片
     */
    public void downloadImages(String username, List<Picture> pictures, String outputDir) {
        if (pictures == null || pictures.isEmpty()) {
            return;
        }

        ExecutorService executor = Executors.newFixedThreadPool(3);
        List<Future<?>> futures = new ArrayList<>();

        for (Picture picture : pictures) {
            Future<?> future = executor.submit(() -> {
                downloadImage(picture.getImgSrc(), outputDir, username);
            });
            futures.add(future);
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                log.error("线程执行异常: " + e.getMessage(), e);
            }
        }

        executor.shutdown();
    }

    /**
     * 从CSV文件中提取图片链接并下载图片
     */
    public void downloadImagesFromCsv(String csvFilePath) {
        Path csvPath = Paths.get(csvFilePath);
        if (!Files.exists(csvPath)) {
            log.error("CSV文件不存在: " + csvPath.toString());
            return;
        }

        // 图片输出目录
        Path imagesDir = csvPath.getParent().resolve("images");
        try {
            Files.createDirectories(imagesDir);
        } catch (IOException e) {
            log.error("创建图片目录失败: " + e.getMessage(), e);
            return;
        }

        int downloadedCount = 0;
        int skippedCount = 0;
        int errorCount = 0;

        try (BufferedReader reader = Files.newBufferedReader(csvPath)) {
            String line;
            String[] headers = null;
            int rowNum = 1;

            while ((line = reader.readLine()) != null) {
                try {
                    String[] values = line.split(",", -1); // -1保留空值
                    
                    if (rowNum == 1) {
                        headers = values;
                        // 检查必要的列是否存在
                        boolean hasPictures = false;
                        boolean hasUpname = false;
                        for (String header : headers) {
                            if ("pictures".equals(header.trim())) hasPictures = true;
                            if ("upname".equals(header.trim())) hasUpname = true;
                        }
                        
                        if (!hasPictures || !hasUpname) {
                            log.error("CSV文件缺少必要的列：pictures 或 upname");
                            return;
                        }
                        rowNum++;
                        continue;
                    }

                    // 构建行数据映射
                    Map<String, String> row = new HashMap<>();
                    for (int i = 0; i < headers.length && i < values.length; i++) {
                        row.put(headers[i].trim(), values[i].trim());
                    }

                    String picturesStr = row.getOrDefault("pictures", "");
                    String username = row.getOrDefault("upname", "unknown");

                    if (picturesStr.isEmpty()) {
                        rowNum++;
                        continue;
                    }

                    // 解析图片URL（以分号分隔）
                    String[] pictureUrls = Arrays.stream(picturesStr.split(";"))
                                                  .map(String::trim)
                                                  .filter(url -> !url.isEmpty())
                                                  .toArray(String[]::new);

                    if (pictureUrls.length == 0) {
                        rowNum++;
                        continue;
                    }

                    // 为每个图片URL创建Picture对象并下载
                    for (String pictureUrl : pictureUrls) {
                        try {
                            // 检查图片是否已存在
                            String[] urlParts = pictureUrl.split("/");
                            String imgName = urlParts[urlParts.length - 1];
                            Path outputFile = imagesDir.resolve(username + "_" + imgName);

                            if (Files.exists(outputFile)) {
                                log.info("图片已存在，跳过: " + outputFile.getFileName());
                                skippedCount++;
                                continue;
                            }

                            // 下载图片
                            downloadImage(pictureUrl, imagesDir.toString(), username);
                            downloadedCount++;

                        } catch (Exception e) {
                            log.error("下载图片失败 (" + pictureUrl + "): " + e.getMessage(), e);
                            errorCount++;
                        }
                    }

                } catch (Exception e) {
                    log.warn("处理第" + rowNum + "行时出错: " + e.getMessage(), e);
                    errorCount++;
                }
                rowNum++;
            }

            log.info("图片下载完成: 新下载 " + downloadedCount + " 张，跳过 " + skippedCount + " 张，失败 " + errorCount + " 张");

        } catch (IOException e) {
            log.error("从CSV文件下载图片时出错: " + e.getMessage(), e);
        }
    }
}
